package com.gjs.reviewtree.web;

import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public CommonResult<?> defaultExceptionHandler(HttpServletResponse response, Exception ex) {
        String msg = "未知服务器错误";
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex0 = (MethodArgumentNotValidException) ex;
            FieldError fieldError = ex0.getBindingResult().getFieldError();
            msg = fieldError.getDefaultMessage();
        } else if (ex instanceof IllegalArgumentException) {
            msg = ex.getMessage();
        }
        return CommonResult.error(HttpStatus.BAD_REQUEST.value(), msg);
    }

}
